//
//  LogViewController.m
//  SSC
//
//  Created by 红沙尘 on 17/6/6.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "LogViewController.h"
#import "SQLITE.h"
#import "HSCLogCell.h"
#import "HSCLog.h"
#import "URLViewController.h"



@interface LogViewController ()<UITableViewDelegate,UITableViewDataSource,
                                UIPopoverPresentationControllerDelegate,URLViewControllerDelegate,
                                HSCLogCellDelegate>
{
    __weak IBOutlet UITableView *logTableView;
    URLViewController *urlPopover;
    
    NSInteger logCount;
    
    NSMutableDictionary *managerDict;
}

@property (nonatomic, copy) NSString *elementKey;
@property (nonatomic, copy) NSString *elementValue;

@end

@implementation LogViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    managerDict = [[NSMutableDictionary alloc] init];
    
    logTableView.tableFooterView = [UIView new];
    logTableView.rowHeight       = UITableViewAutomaticDimension;
    logTableView.estimatedRowHeight = 50;
    
    [logTableView registerNib:[UINib nibWithNibName:@"HSCLogCell" bundle:nil]
       forCellReuseIdentifier:@"HSCLogCell"];
    
    [self loadDataWithKey:@"id" value:nil];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(showSearch)];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(0, 0, 44, 44);
    [btn setTitle:@"关闭" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - event

- (void)loadDataWithKey:(NSString *)key value:(NSString *)value {
    self.elementKey   = key;
    self.elementValue = value;
    logCount = [[SQLITE standardSqlite] counttable:Table_Log key:self.elementKey value:self.elementValue];
    [logTableView reloadData];
}

- (void)showSearch {
    
    CGSize size = [UIScreen mainScreen].bounds.size;
    
    CGSize contentSize = CGSizeMake(size.width - 10, size.height - 150);
    
    urlPopover = [[URLViewController alloc] init];
    urlPopover.urlDelegate = self;
    urlPopover.modalPresentationStyle = UIModalPresentationPopover;
    
    //设置依附的按钮
    urlPopover.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItem;
    
    //可以指示小箭头颜色
    urlPopover.popoverPresentationController.backgroundColor = [UIColor whiteColor];
    
    //content尺寸
    urlPopover.preferredContentSize = contentSize;
    
    //pop方向
    urlPopover.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
    //delegate
    urlPopover.popoverPresentationController.delegate = self;
    
    [self presentViewController:urlPopover animated:YES completion:nil];
}

- (void)hideSearch {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(showSearch)];
    
    [self loadDataWithKey:@"id" value:nil];
}

#pragma mark - HSCLogCellDelegate

- (void)modelStateChanged:(HSCLogCell *)cell {

    [logTableView reloadData];
}

#pragma mark - URLViewControllerDelegate

- (void)didSelectedWithKey:(NSString *)key url:(NSString *)url {
    
    [self loadDataWithKey:key value:url];
    
    [urlPopover dismissViewControllerAnimated:YES completion:nil];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(hideSearch)];
}



#pragma mark - UIPopoverPresentationControllerDelegate
//代理方法 ,点击即可dismiss掉每次init产生的PopViewController
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller{
    return UIModalPresentationNone;
}

#pragma mark -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    self.navigationItem.titleView = [self titleLabelWithCount:logCount];
    
    return logCount;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HSCLogCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HSCLogCell"];
    cell.logDelegate = self;
    
    int offset = (int)indexPath.section;

    NSString *sql = @"";
    
    if (self.elementKey.length > 0 && self.elementValue.length > 0) {
        sql = [NSString stringWithFormat:@"select * from %@ where %@='%@' ORDER by id desc limit 1 offset %d",Table_Log,self.elementKey,self.elementValue,offset];
    } else {
        sql = [NSString stringWithFormat:@"select * from %@ ORDER by id desc limit 1 offset %d",Table_Log,offset];
    }
    
    NSArray *array = [[SQLITE standardSqlite] selectDataWithSQL:sql table:Table_Log];
    
    if (array.count > 0) {
        
        NSDictionary *dict = array[0];
        
        [cell loadWithDict:dict];
        [cell loadWithStateModel:[self logModelWitId:dict[@"id"]]];
    } else {
        [cell loadWithDict:nil];
        [cell loadWithStateModel:nil];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HSCLogCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = [HSCLog dataTOjsonString:cell.logDict];
    
    NSString *msg = @"数据已经复制到剪贴板";
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
                                                                             message:msg
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (LogStateModel *)logModelWitId:(NSString *)aid {
    
    LogStateModel *model = managerDict[aid];
    
    if (!model) {
        model = [[LogStateModel alloc] init];
        model.show = YES;
        managerDict[aid] = model;
    }
    
    return managerDict[aid];
}

#pragma mark - setup 

- (UILabel *)titleLabelWithCount:(NSInteger)count {
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = [NSString stringWithFormat:@"共%d条",(int)count];
    
    
    return titleLabel;
}

@end


